<template>
  <div class="app-container">
    <el-form label-width="120px">

      <el-form-item label="角色名称">
        <el-input v-model="role.name" style="width: 300px;"/>
      </el-form-item>

      <el-form-item label="角色描述">
        <el-input v-model="role.description" style="width: 300px;"/>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import role from '@/api/management/role'

export default {
  data() {
    return {
      role: "",
      //防止重复点击提交按钮
      saveBtnDisabled: false
    }
  },
  created() {
    this.init()
  },
  watch: {
    $route(to, from) {
      //路由发生变化时，执行初始化方法
      this.init()
    }
  },
  methods: {
    init() {
      //判断是否有ID值，有的话说明是修改操作，需要回显
      if (this.$route.params && this.$route.params.id) {
        //从路径中获取ID值
        const id = this.$route.params.id
        //调用跟ID值查询的方法
        this.getInfo(id)
      } else {
        //路径中没有ID，为新增，需要清空表单
        this.role = {}
      }
    },
    //根据讲师ID查询讲师
    getInfo(id) {
      role.getRoleById(id)
        .then(response => {
          this.role = response.data.role
        })
    },
    saveOrUpdate() {
      if (this.role.id) {
        this.updateRoleInfo()
      } else {
        this.addRole()
      }
    },
    updateRoleInfo() {
      //更新用户信息
      role.updateRoleInfo(this.role)
        .then(response => {
          this.$message({
            type: 'success',
            message: '更新成功!'
          });
          //回到列表页面
          this.$router.push({path: '/role/table'})
        })
    },
    //添加讲师
    addRole() {
      role.addUser(this.role)
        .then(response => {
          //提示添加成功
          this.$message({
            type: 'success',
            message: '添加成功!'
          });
          //回到列表页面
          this.$router.push({path: '/role/table'})
        })
    }
  }
}
</script>
